<template>
  <el-form :model="form" status-icon :rules="rules" ref="form" label-width="100px" class="login-container">
    <h3 class="login-title">系统登录</h3>
    <el-form-item label="用户名" label-width="80px" prop="username" class="username">
      <el-input type="input" v-model="form.username" autocomplete="off" placeholder="请输入账号"></el-input>
    </el-form-item>

    <el-form-item label="密码" label-width="80px" prop="password" class="password">
      <el-input type="password" v-model="form.password" autocomplete="off" placeholder="请输入密码"></el-input>
    </el-form-item>

    <el-form-item class="login-submit">
      <el-button type="success" @click="login">登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {getMenu} from "@/http/data";

export default {
  name: "Login",
  data() {
    return {
      form: {},
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, message: '用户名长度不能小于3位', trigger: 'blur'},
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
        ]
      }
    }
  },
  methods: {
    // 登录事件
    login() {
      getMenu(this.form).then(({data: res}) => {
        if (res.code === 200) {
          // 清除之前导航菜单
          this.$store.commit('tab/clearMenu')
          // 将接收的导航菜单存到state和cookie中
          this.$store.commit('tab/setMenu', res.data.menu)
          // 将接收的token和用户信息保存到state和cookie中
          this.$store.commit('login/setUserInfo', {
            ...res.data.userInfo, token: res.data.token
          })
          // 将接收的menu添加component并注册组件路由
          this.$store.commit('tab/addMenu')
          // 跳转到主页
          this.$router.push({name: 'home'})
        } else {
          this.$message.warning(res.data.message) /*通知错误信息*/
        }
      })
    },
  },
}
</script>

<style scoped>
.login-container {
  border-radius: 15px;
  background-clip: padding-box;
  margin: 180px auto;
  width: 350px;
  padding: 35px 35px 15px;
  background-color: #ffffff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;
}

.login-title {
  margin: 0 auto 40px;
  text-align: center;
  color: #505458;
}

.login-submit {
  width: 100%;
  margin: 20px auto 0;
}

.login-submit .el-button {
  width: 180px;
  margin: -10px;
}
</style>
